package com.hockeo.server.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.hockeo.server.data.DAO;
import com.hockeo.shared.domain.persistent.Image;
import com.hockeo.tinygds.TKey;
import com.hockeo.tinygds.TinyGDS;

/**
 * Serves images from the datastore.
 *
 * @version $Id$
 * @author jjanke
 */
public class ImageServlet extends HttpServlet
{
  private static final long   serialVersionUID = 1L;
  private static final Logger d_log            = Logger.getLogger( ImageServlet.class.getName() );
  private static final String PARAM_ID         = "id";
  private static final int    CACHE_MAX_AGE    = 3600 * 24 * 28;

  @Override
  protected void doGet( HttpServletRequest rq, HttpServletResponse rp ) throws ServletException, IOException
  {
    doPost( rq, rp );
  }

  @Override
  protected void doPost( HttpServletRequest rq, HttpServletResponse rp ) throws ServletException, IOException
  {
    String strKey = rq.getParameter( PARAM_ID );

    if ( strKey == null )
    {
      d_log.log( Level.FINER, "ImageServlet called without " + PARAM_ID + " parameter." );
      return;
    }

    TinyGDS tgds = DAO.get().begin();
    TKey<Image> key = new TKey<Image>( Image.class, strKey );
    Image img;

    try
    {
      img = tgds.get( key );
    }
    catch ( EntityNotFoundException ex )
    {
      d_log.log( Level.FINER, "Found no image for key: " + key.toString() + "" );
      return;
    }

    // cache all images for 28 days (4 weeks)
    //
    rp.setHeader( "Cache-control", "max-age=" + CACHE_MAX_AGE );
    rp.setContentType( img.getMimeType() );
    rp.setContentLength( img.getData().length );

    OutputStream out = rp.getOutputStream();
    out.write( img.getData() );
    out.close();
  }
}
